package com.edu.framework.websocket.assemble.message;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.edu.common.utils.StringUtils;
import com.edu.framework.websocket.service.LessonRemindService;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * @program: xxxx_2
 * @description:
 * @author: zlh
 * @create: 2024-01-15 09:49
 **/
@Slf4j
@Component
public class TriggerMsgEngine {

  private static Map<String, MessageAssemble> messageAssembleMap = new HashMap<>();

  private static Map<String, Map<Date, List<Long>>> msgDatePool = new HashMap<>();

  private static List<String> everyTimeRunPool = new ArrayList<>();

  @Autowired
  public TriggerMsgEngine(ApplicationContext applicationContext){
    messageAssembleMap = applicationContext.getBeansOfType(MessageAssemble.class);
    initMsgDataPool();
  }

  /**
   * 初始化
   */
  public static void initMsgDataPool(){
    msgDatePool = new HashMap<>();
    messageAssembleMap.forEach((k ,v)-> v.buildTrigger(new ArrayList<>()));
    log.info("消息下发引擎 初始化完成。");
//    log.info("msgDatePool:{}", JSONObject.toJSONString(msgDatePool));
  }

  /**
   * 添加触发时间
   * @param item
   */
  public static void addMsgDate(List<MsgCacheDTO> item){
    Map<String, List<MsgCacheDTO>> collect = item.stream().collect(Collectors.groupingBy(MsgCacheDTO::getClsName));

    collect.forEach((clsName, v) -> {
      Map<Date, List<Long>> collect1 = v.stream()
          .collect(Collectors.toMap(MsgCacheDTO::getTriggerTime, MsgCacheDTO::getClassIds, (x, y) -> {
            x.addAll(y);
            return x.stream().distinct().collect(Collectors.toList());
          }));
      log.info("消息下发引擎 更新下发时间:{}", JSONObject.toJSONString(collect1));
      msgDatePool.put(StringUtils.toLowerCamel(clsName), collect1);
    });
  }

  /**
   * 每次心跳都执行，加入everyTimeRunPool
   * @param clsName
   */
  public static void addEveryRun(String clsName){
    everyTimeRunPool.add(StringUtils.toLowerCamel(clsName));
  }

  /**
   * 执行发送
   */
  public static void runPushMsg(){
    // 课程提醒 每次都执行
    String cls = LessonRemindService.class.getSimpleName();
    messageAssembleMap.get(StringUtils.toLowerCamel(cls)).pushMsg(new ArrayList<>());

    int size = everyTimeRunPool.size();
    Date date = new Date();
    int num =  (int) (DateUtil.minute(date)) % size;
    // 每次轮流执行
//    messageAssembleMap.get(everyTimeRunPool.get(num)).pushMsg(new ArrayList<>());


// todo 测试阶段
    everyTimeRunPool.forEach(a -> {
      messageAssembleMap.get(a).pushMsg(new ArrayList<>());
    });


    // 检查时间执行
//    Date now = new Date();
//    msgDatePool.forEach((k, v) ->{
//      AtomicReference<Date> tmp = new AtomicReference<>();
//      v.forEach((date, classIds) -> {
//        if (date.before(now)){
//          tmp.set(date);
//          messageAssembleMap.get(k).pushMsg(classIds);
//        }
//      });
//      if (tmp.get() != null){
//        v.remove(tmp.get());
//      }
//    });
  }


}
